<template>
  <div class="message-item" :class="{'alignright': messagePosition=='position-right'}">
    <div class="mes-div-left" v-if="messagePosition=='position-left'">
      <div class="peo-info">
        <avatar :src="avatar" :classname="'width-68'" v-mlongpress="fnaite" />
        <p>{{message.healthManagerTypeName}}</p>
        <h5>{{from}}</h5>
      </div>
      <div class="chat-info">
        <div class="send-time">{{date}}</div>
        <div class="send-con" @touchstart="gtouchstart" @touchmove="gtouchmove" @touchend="gtouchend">
            <!-- {{message.payload}} -->
          <text-element v-if="message.type === TIM.TYPES.MSG_TEXT" :payload="message.payload" :message="message" />
          <face-element v-else-if="message.type === TIM.TYPES.MSG_FACE" :payload="message.payload" :message="message" />
          <image-element v-else-if="message.type === TIM.TYPES.MSG_IMAGE" :payload="message.payload" :message="message" :imageArr="imageArr" />
          <video-element v-else-if="message.type === TIM.TYPES.MSG_VIDEO" :payload="message.payload" :message="message" />
          <sound-element v-else-if="message.type === TIM.TYPES.MSG_SOUND" :payload="message.payload" :message="message" :isMine="isMine" />
          <!-- <ul class="touch-group">
            <li v-if="isMine&&!isTimeout" @click="fnrevokeMessage">撤回</li>
            <li v-if="message.type === TIM.TYPES.MSG_TEXT" @click="fncopymessage">复制</li>
          </ul> -->
          <custom-element v-else-if="message.type === TIM.TYPES.MSG_CUSTOM" :payload="message.payload" :message="message" :isMine="isMine" />
           <quote-element v-if="message.type === TIM.TYPES.MSG_CUSTOM" :payload="message.payload" :message="message" :isMine="isMine" />
        </div>
      </div>
     
    </div>
    <div class="mes-div-right" v-if="messagePosition=='position-right'">
      <!-- <div class="send-time">{{date}}<span v-if="message.type === TIM.TYPES.MSG_CUSTOM">打卡消息</span></div> -->
      <div class="send-time">{{date}}</div>
      <div class="chat-info">
        <div class="peo-img">
          <avatar :src="avatar" :imgType="1" @touchstart.stop />
        </div>
        <div class="send-con">
          <text-element v-if="message.type === TIM.TYPES.MSG_TEXT" :payload="message.payload" :message="message" :isMine="isMine" />
          <face-element v-else-if="message.type === TIM.TYPES.MSG_FACE" :payload="message.payload" :message="message" />
          <image-element v-else-if="message.type === TIM.TYPES.MSG_IMAGE" :payload="message.payload" :message="message" :imageArr="imageArr" />
          <video-element v-else-if="message.type === TIM.TYPES.MSG_VIDEO" :payload="message.payload" :message="message" />
          <sound-element v-else-if="message.type === TIM.TYPES.MSG_SOUND" :payload="message.payload" :message="message" :isMine="isMine" />
          <custom-element v-else-if="message.type === TIM.TYPES.MSG_CUSTOM" :payload="message.payload" :message="message" :isMine="isMine" />
        </div>
      </div>
       <quote-element v-if="message.type === TIM.TYPES.MSG_CUSTOM" :payload="message.payload" :message="message" :isMine="isMine" />
    </div>
    <div class="mes-div-center" v-if="messagePosition=='position-center'">
      <div class="send-time">{{date}}</div>
      <!--系统消息-->
      <div class="send-text" v-if="message.type === TIM.TYPES.MSG_GRP_TIP">{{centertext}}</div>
      <div class="send-text" v-else-if="message.type === TIM.TYPES.MSG_GRP_SYS_NOTICE">{{centertext}}</div>
      <!--撤回的消息-->
      <div class="send-text" v-else-if="message.isRevoked">
        {{centertext}}
        <span class="edit-button" v-show="isEdit" @click="reEdit">&nbsp;重新编辑</span>
      </div>
    </div>
  </div>
</template>

<script>
var timeOutEvent=null;
import { mapState } from 'vuex'
import { getFullDate } from '../../utils/date'
import { translateGroupSystemNotice } from '../../utils/common'
import TextElement from './message-elements/text-element.vue'
import FaceElement from './message-elements/face-element.vue'
import ImageElement from './message-elements/image-element.vue'
import VideoElement from './message-elements/video-element.vue'
import SoundElement from './message-elements/sound-element.vue'
import CustomElement from './message-elements/custom-element.vue'
import QuoteElement from './message-elements/quote-element.vue'
// import GroupTipElement from './message-elements/group-tip-element.vue'
export default {
  name: 'MessageItem',
  data(){
    return {
      isTimeout: false,
    }
  },
  props: {
    message: {
      type: Object,
      required: true
    },
    imageArr: {
      type: Array,
      required: false,
      default: []
    }
  },
  components: {
    TextElement,
    FaceElement,
    ImageElement,
    VideoElement,
    SoundElement,
    CustomElement,
    QuoteElement
    // GroupTipElement,
  },
  computed: {
    ...mapState({
      currentConversation: state => state.conversation.currentConversation,
      currentUserProfile: state => state.user.currentUserProfile,
      nowtime: state => state.user.nowtime
    }),
    date() {
      // return getFullDate(new Date(this.message.time * 1000))
      if(!this.message.time){
        return '';
      }
      var dateTimeStamp = this.message.time * 1000;
      var result = '';
      var now = this.nowtime;
      var diffValue = now - dateTimeStamp;
      var yearC = diffValue / 31104000000;
      var monthC = diffValue / 2592000000;
      var weekC = diffValue / (7 * 86400000);
      var dayC = diffValue / 86400000;
      var hourC = diffValue / 3600000;
      var minC = diffValue / 60000;
      if (yearC >= 1) {
        // result = parseInt(yearC) + "年前";
        result = getFullDate(new Date(dateTimeStamp))
      } else if (monthC >= 1) {
        result = getFullDate(new Date(dateTimeStamp))
        // result = parseInt(monthC) + "个月前";
      } else if (weekC >= 1) {
        result = getFullDate(new Date(dateTimeStamp))
        // result = parseInt(weekC) + "周前";
      } else if (dayC >= 1) {
        result = getFullDate(new Date(dateTimeStamp))
        // result = parseInt(dayC) + "天前";
      } else if (hourC >= 1) {
        // result = getFullDate(new Date(dateTimeStamp))
        result = parseInt(hourC) + "小时前";
      } else if (minC >= 1) {
        result = parseInt(minC) + "分钟前";
      } else {
        result = "刚刚";
      }
      return result;
    },
    avatar() {
      if (this.currentConversation.type === 'C2C') {
        let imgurl = this.isMine
          ? this.currentUserProfile.avatar
          : this.currentConversation.userProfile.avatar
        if(!imgurl&&this.isMine){
          return 'https://webtest.miaomore.com/test/activity/common/images/one-img03.png';
        }
        return imgurl;
      } else if (this.currentConversation.type === 'GROUP') {
        let imgurl = this.isMine
          ? this.currentUserProfile.avatar
          : this.message.avatar
        if(!imgurl&&this.isMine){
          return 'https://webtest.miaomore.com/test/activity/common/images/one-img03.png';
        }
        return imgurl;
      } else {
        if(this.message.avatar){
          return this.message.avatar
        }else{
          return ''
        }
       
      }
    },
    from() {
      const isC2C = this.currentConversation.type === this.TIM.TYPES.CONV_C2C
      // 自己发送的用昵称渲染
      if (this.isMine) {
        return this.currentUserProfile.nick || this.currentUserProfile.userID
      }
      // 1. C2C 的消息体中还无 nick / avatar 字段，需从 conversation.userProfile 中获取
      if (isC2C) {
        return (
          this.currentConversation.userProfile.nick ||
          this.currentConversation.userProfile.userID
        )
      } else if (this.currentConversation.type === this.TIM.TYPES.CONV_SYSTEM) {
        return this.message.type === this.TIM.TYPES.MSG_GRP_SYS_NOTICE
          ? '群系统通知'
          : '系统通知'
      }
      // 2. 群组消息，用消息体中的 nick 渲染。nameCard暂时支持不完善
      var formstr = this.message.from
      if(formstr=='administrator'){
        formstr = '管理员'
      }
      return this.message.nick || formstr
    },
    messagePosition() {
      if (
        ['TIMGroupTipElem', 'TIMGroupSystemNoticeElem'].includes(
          this.message.type
        )
      ) {
        return 'position-center'
      }
      if (this.message.isRevoked) { // 撤回消息
        return 'position-center'
      }
      var questionResult=false;
      try{
        if(JSON.parse(this.message.payload.data).type==5){
          questionResult=true
        }
      }catch(e){}
      if(this.message.type === 'TIMCustomElem'&&questionResult){
        return 'position-center'
      }
      if (this.isMine) {
        return 'position-right'
      } else {
        return 'position-left'
      }
    },
    isMine() {
      return this.message.flow === 'out'
    },
    centertext() {
      if(this.message.type === this.TIM.TYPES.MSG_GRP_TIP){
        return this.getGroupTipContent(this.message)
      }else if(this.message.type === this.TIM.TYPES.MSG_GRP_SYS_NOTICE){
        return translateGroupSystemNotice(this.message)
      }else if(this.message.isRevoked){
        if (this.message.conversationType === 'C2C' && !this.isMine) {
          return '对方撤回了一条消息'
        }
        if (this.message.conversationType === 'GROUP' && !this.isMine) {
          var meform = this.message.from
          if(this.message.nick){
            meform = this.message.nick
          }
          return `${meform}撤回了一条消息`
        }
        return '你撤回了一条消息'
      }
    },
    isEdit() {
      if (!this.isMine) {
        return false
      }
      if (this.message.type !== this.TIM.TYPES.MSG_TEXT) {
        return false
      }
      if (this.isTimeout) {
        return false
      }
      return true
    },
  },
  created(){
    this.isTimeoutHandler()
  },
  methods:{
    fnaite(){
      if(this.currentConversation.type === 'GROUP'){
        this.$emit('fnaiteItem',this.from)
      }
    },
    fncopymessage(){
      document.getElementById("copy-text").value=this.message.payload.text;
      document.getElementById("copy-text").select();
      document.execCommand("Copy"); 
    },
    getGroupTipContent(message) {
      var nickList=[];
      if(!message.nick){
        for(var i=0;i<message.payload.userIDList.length;i++){
          for(var j=0;j<this.currentMemberList.length;j++){
            if(this.currentMemberList[j].userID == message.payload.userIDList[i]){
              nickList.push(this.currentMemberList[j].nick)
              break ;
            }
          }
        }
      }
      const userName = message.nick || nickList.join(',')
      switch (message.payload.operationType) {
        case this.TIM.TYPES.GRP_TIP_MBR_JOIN:
          return `群成员：${userName} 加入群组`
        case this.TIM.TYPES.GRP_TIP_MBR_QUIT:
          return `群成员：${userName} 退出群组`
        case this.TIM.TYPES.GRP_TIP_MBR_KICKED_OUT:
          // return `群成员：${userName} 被${message.payload.operatorID}踢出群组`
          return `${userName}退出群组，将会重新为您分配其他管理师`
        case this.TIM.TYPES.GRP_TIP_MBR_SET_ADMIN:
          return `群成员：${userName} 成为管理员`
        case this.TIM.TYPES.GRP_TIP_MBR_CANCELED_ADMIN:
          return `群成员：${userName} 被撤销管理员`
        case this.TIM.TYPES.GRP_TIP_GRP_PROFILE_UPDATED:
          return '群资料修改'
        case this.TIM.TYPES.GRP_TIP_MBR_PROFILE_UPDATED:
          for (let member of message.payload.memberList) {
            if (member.muteTime > 0) {
              return `群成员：${member.userID}被禁言${member.muteTime}秒`
            } else {
              return `群成员：${member.userID}被取消禁言`
            }
          }
          break
        default:
          return '[群提示消息]'
      }
    },
    reEdit() {
      this.$bus.$emit('reEditMessage', this.message.payload.text)
    },
    isTimeoutHandler() { // 从发送消息时间开始算起，两分钟内可以编辑
      let now = new Date()
      if (parseInt(now.getTime() / 1000) - this.message.time > 2 * 60) {
        this.isTimeout = true
        return
      }
      setTimeout(this.isTimeoutHandler, 1000)
    },
    fnrevokeMessage(){
      this.tim.revokeMessage(this.message).then(() => {
        this.isTimeoutHandler()
      }).catch((err) => {
        this.$store.commit('showMessage', {
          message: err,
          type: 'warning'
        })
      })
    },
    gtouchstart(item){
      timeOutEvent = setTimeout(function(){
        timeOutEvent = 0;
      },1500);
      return false;
    },
    gtouchend(item){
      clearTimeout(timeOutEvent);//清除定时器
      // if(timeOutEvent!=0){
      //   //这里写要执行的内容（尤如onclick事件）
      //   vm.goChat(item);
      // }
      return false;
    },
    gtouchmove(){
      clearTimeout(timeOutEvent);//清除定时器
      timeOutEvent = 0;
    },
  }
}
</script>

<style lang="scss" scoped>
  .message-item{
    margin-bottom: .346667rem;
    width: 100%;
    &.alignright{
      text-align: right;
    }
    .mes-div-left{
      // background: rgba($color: #ffffff, $alpha: 0.6);
      background: #f5f4fe;
      box-shadow: 0 .08rem .106667rem 0 rgba(135,127,254,0.23);
      border-radius: .266667rem;
      max-width: 100%;
      display: inline-block;
      position: relative;
      padding-left: 1.88rem;
      min-height: 2.186667rem;
      .peo-info{
        position: absolute;
        width: 1.8rem;
        left: .066667rem;
        top: .33rem;
        text-align: center;
        p{
          font-size: .24rem;
          width: 100%;
          line-height: .373333rem;
          min-height: .373333rem;
          color: #9B9B9B;
          letter-spacing: 0;
          margin-top: .08rem;
          @include ellipsis();
        }
        h5{
          font-size: .266667rem;
          width: 100%;
          line-height: .373333rem;
          color: black;
          letter-spacing: 0;
          @include ellipsis();
        }
      }
      .chat-info{
        background: #fcfbfe;
        box-shadow: 0 .08rem .266667rem 0 rgba(63,35,245,0.10);
        border-radius: .266667rem;
        width: 100%;
        min-height: 2.186667rem;
        position: relative;
        padding: .213333rem .24rem .253333rem .44rem;
        &::before{
          width: 0px;
          height: 0px;
          position: absolute;
          top: .663333rem;
          left: -.32rem;
          border: .173333rem solid;
          border-color: transparent #fcfbfe transparent transparent;
          content:'';
        }
        .send-time{
          font-size: .266667rem;
          color: #9B9B9B;
          line-height: .373333rem;
          margin-bottom: .133333rem;
        }
        .send-con{
          width: 100%;
        }
      }
    }
    .mes-div-right{
      max-width: 100%;
      min-width: 4.8rem;
      padding-left: 1.866667rem;
      display: inline-block;
      text-align: left;
      .send-time{
        padding-left: .106667rem;
        font-size: .266667rem;
        color: #000000;
        letter-spacing: 0;
        line-height: .373333rem;
        margin-bottom: .08rem;
        span{
          color: #9B9B9B;
          margin-left: .066667rem;
        }
      }
      .chat-info{
        width: 100%;
        padding-right: 1.04rem;
        position: relative;
        // min-height: 1.546667rem;
        min-height: 1.2rem;
        .peo-img{
          width: .8rem;
          height: .8rem;
          position: absolute;
          right: .026667rem;
          // top: .373333rem;
          top: .2rem;
        }
        .send-con{
          position: relative;
          max-width: 100%;
          // min-height: 1.546667rem;
          min-height: 1.2rem;
          padding: .293333rem .346667rem .373333rem .426667rem;
          background: #FFFFFF;
          border: .026667rem solid $acolor;
          border-radius: .266667rem;
          &::after{
            width: 0px;
            height: 0px;
            position: absolute;
            // top: .6rem;
            top: .426667rem;
            right: -.32rem;
            border: .173333rem solid;
            border-color: transparent transparent transparent white;
            content:'';
          }
          &::before{
            width: 0px;
            height: 0px;
            position: absolute;
            // top: .6rem;
            top: .426667rem;
            right: -.346667rem;
            border: .173333rem solid;
            border-color: transparent transparent transparent $acolor;
            content:'';
          }
        }
      }
    }
    .mes-div-center{
      width: 100%;
      text-align: center;
      .send-time{
        font-size: .266667rem;
        color: #9B9B9B;
        line-height: .373333rem;
        margin-bottom: .106667rem;
      }
      .send-text{
        width: 100%;
        font-size: .266667rem;
        color: #9B9B9B;
        letter-spacing: 0;
        text-align: center;
        line-height: .533333rem;
        .edit-button{
          color: $acolor;
        }
      }
    }
  }
</style>
